<?php
namespace app\admin\controller;

use think\facade\Db;

class System extends \app\BaseController
{
    /**
     * 系统状态页面
     */
    public function index()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return redirect('/admin/login');
        }
        
        // 获取系统信息
        $systemInfo = $this->getSystemInfo();
        
        // 获取数据库信息
        $databaseInfo = $this->getDatabaseInfo();
        
        // 获取服务器信息
        $serverInfo = $this->getServerInfo();
        
        // 获取应用信息
        $appInfo = $this->getAppInfo();
        
        // 准备视图数据
        $data = [
            'title' => '系统状态',
            'current_menu' => 'system',
            'system_info' => $systemInfo,
            'database_info' => $databaseInfo,
            'server_info' => $serverInfo,
            'app_info' => $appInfo,
            'admin_user' => $_SESSION['admin_user']
        ];
        
        return view('system/index', $data);
    }
    
    /**
     * 获取系统信息
     */
    private function getSystemInfo()
    {
        return [
            'php_version' => PHP_VERSION,
            'os' => PHP_OS,
            'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'memory_limit' => ini_get('memory_limit'),
            'max_execution_time' => ini_get('max_execution_time'),
            'upload_max_filesize' => ini_get('upload_max_filesize'),
            'post_max_size' => ini_get('post_max_size'),
            'timezone' => date_default_timezone_get(),
            'current_time' => date('Y-m-d H:i:s'),
        ];
    }
    
    /**
     * 获取数据库信息
     */
    private function getDatabaseInfo()
    {
        try {
            // 获取数据库版本
            $version = Db::query('SELECT VERSION() as version')[0]['version'] ?? 'Unknown';
            
            // 获取数据库大小
            $dbName = config('database.connections.mysql.database');
            $sizeQuery = "SELECT 
                ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb
                FROM information_schema.tables 
                WHERE table_schema = '{$dbName}'";
            $sizeResult = Db::query($sizeQuery);
            $dbSize = $sizeResult[0]['size_mb'] ?? 0;
            
            // 获取表数量
            $tableCount = count(Db::getTables());
            
            // 测试连接
            $connectionStatus = 'connected';
            $connectionTime = microtime(true);
            Db::query('SELECT 1');
            $connectionTime = round((microtime(true) - $connectionTime) * 1000, 2);
            
        } catch (\Exception $e) {
            $version = 'Connection Failed';
            $dbSize = 0;
            $tableCount = 0;
            $connectionStatus = 'failed';
            $connectionTime = 0;
        }
        
        return [
            'version' => $version,
            'size' => $dbSize . ' MB',
            'table_count' => $tableCount,
            'status' => $connectionStatus,
            'connection_time' => $connectionTime . ' ms',
        ];
    }
    
    /**
     * 获取服务器信息
     */
    private function getServerInfo()
    {
        // 获取磁盘使用情况
        $diskTotal = disk_total_space('.');
        $diskFree = disk_free_space('.');
        $diskUsed = $diskTotal - $diskFree;
        $diskUsagePercent = round(($diskUsed / $diskTotal) * 100, 2);
        
        // 获取内存使用情况
        $memoryUsage = memory_get_usage(true);
        $memoryPeak = memory_get_peak_usage(true);
        
        return [
            'disk_total' => $this->formatBytes($diskTotal),
            'disk_used' => $this->formatBytes($diskUsed),
            'disk_free' => $this->formatBytes($diskFree),
            'disk_usage_percent' => $diskUsagePercent,
            'memory_usage' => $this->formatBytes($memoryUsage),
            'memory_peak' => $this->formatBytes($memoryPeak),
            'load_average' => $this->getLoadAverage(),
        ];
    }
    
    /**
     * 获取应用信息
     */
    private function getAppInfo()
    {
        $thinkVersion = \think\App::VERSION;
        
        // 检查关键目录权限
        $directories = [
            'runtime' => is_writable(runtime_path()),
            'public/uploads' => is_writable(public_path() . 'uploads'),
            'config' => is_readable(config_path()),
        ];
        
        // 检查关键文件
        $files = [
            '.env' => file_exists(root_path() . '.env'),
            'composer.json' => file_exists(root_path() . 'composer.json'),
        ];
        
        return [
            'think_version' => $thinkVersion,
            'app_debug' => config('app.app_debug') ? 'ON' : 'OFF',
            'directories' => $directories,
            'files' => $files,
        ];
    }
    
    /**
     * 格式化字节数
     */
    private function formatBytes($bytes, $precision = 2)
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        
        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, $precision) . ' ' . $units[$i];
    }
    
    /**
     * 获取系统负载
     */
    private function getLoadAverage()
    {
        if (function_exists('sys_getloadavg')) {
            $load = sys_getloadavg();
            return implode(', ', array_map(function($val) {
                return round($val, 2);
            }, $load));
        }
        
        return 'N/A';
    }
    
    /**
     * 清理缓存
     */
    public function clearCache()
    {
        // 确保session启动
        if (!session_id()) {
            session_start();
        }
        
        // 简单的登录检查
        if (!isset($_SESSION['admin_user'])) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }
        
        try {
            // 清理runtime缓存
            $this->clearDirectory(runtime_path() . 'cache');
            $this->clearDirectory(runtime_path() . 'temp');
            
            // 记录操作日志
            $adminUser = $_SESSION['admin_user'];
            Db::name('admin_log')->insert([
                'admin_id' => $adminUser['id'],
                'admin_name' => $adminUser['username'],
                'action' => 'clear_cache',
                'description' => '清理系统缓存',
                'target_id' => 0,
                'ip' => $this->request->ip(),
                'user_agent' => $this->request->header('User-Agent'),
                'create_time' => time()
            ]);
            
            return json(['code' => 1, 'msg' => '缓存清理成功']);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '缓存清理失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 清理目录
     */
    private function clearDirectory($dir)
    {
        if (!is_dir($dir)) {
            return;
        }
        
        $files = glob($dir . '/*');
        foreach ($files as $file) {
            if (is_file($file)) {
                unlink($file);
            } elseif (is_dir($file)) {
                $this->clearDirectory($file);
                rmdir($file);
            }
        }
    }
}
